﻿#include "aes_util.h"

#include "qaesencryption.h"
#include <QByteArray>
#include <QCryptographicHash>

#include "system_util.h"

QString AESUtil::encryptBase64(QString src) {
    if (src.isEmpty()) {
        return src;
    }
    QString key = getKey();
    QAESEncryption encryption(QAESEncryption::AES_256, QAESEncryption::ECB, QAESEncryption::Padding::ISO);
    QByteArray hashKey = QCryptographicHash::hash(key.toUtf8(), QCryptographicHash::Sha256);

    QByteArray encodeText = encryption.encode(src.toLocal8Bit(), hashKey);
    if (encodeText.isEmpty()) {
        return "";
    }
    return QString(encodeText.toBase64());
}

QString AESUtil::decryptBase64(QString srcBase64) {
    if (srcBase64.isEmpty()) {
        return "";
    }
    QByteArray decodedData = QByteArray::fromBase64(srcBase64.toUtf8());
    if (decodedData.isEmpty()) {
        return "";
    }
    QString key = getKey();
    QAESEncryption encryption(QAESEncryption::AES_256, QAESEncryption::ECB, QAESEncryption::Padding::ISO);
    QByteArray hashKey = QCryptographicHash::hash(key.toLocal8Bit(), QCryptographicHash::Sha256);

    QByteArray decodedText = encryption.removePadding(encryption.decode(decodedData, hashKey));
    return QString(decodedText);
}

QString AESUtil::getKey() {
    QString serialNumber = cppc::SystemUtil::getDiskSerialNumber();
    return "ep-vpn-client-key-" + serialNumber;
}
